﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler
{
    /// <summary>
    /// 分配角色
    /// </summary>
    public class GetUserRoleHandler : IRequestHandler<GetUserRoleCommand, ApiResult<List<RoleUserDTO>>>
    {
        private readonly IBaseRepository<UserRoleModel> userRoleRepo;
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IMapper mapper;

        public GetUserRoleHandler(IBaseRepository<UserRoleModel> userRoleRepo,IBaseRepository<UserModel> userRepo,IMapper mapper)
        {
            this.userRoleRepo = userRoleRepo;
            this.userRepo = userRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<RoleUserDTO>>> Handle(GetUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<RoleUserDTO>> res = new ApiResult<List<RoleUserDTO>>();
            var user = userRoleRepo.GetAll().Where(x => x.RoleId == request.RoleId).Select(x => x.UserId);
            var userlist = userRepo.GetAll().Where(x => user.Contains(x.Id));
            var model = mapper.Map<List<RoleUserDTO>>(userlist);
            res.Msg = "显示成功";
            res.Code = ApiEnum.Success;
            res.Data = model;
            return Task.FromResult(res);
        }
    }
}
